package com.mystudio.android.calendar.view;

import java.text.SimpleDateFormat;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.mystudio.android.calendar.R;
import com.mystudio.android.calendar.constants.Constants;
import com.mystudio.android.calendar.model.Calendar;
import com.mystudio.android.calendar.model.Instance;
import com.mystudio.android.calendar.util.CPSyncUtil;
import com.mystudio.android.calendar.util.ChineseCalendar;
import com.mystudio.android.util.Logger;

public class MonthView extends LinearLayout {
	private static final Logger logger = new Logger(Constants.LOG_TAG, MonthView.class);
	private TableLayout monthTable;
	private TextView monthTitle;
	private SimpleDateFormat sdf;
	
	public MonthView(Context context, AttributeSet attributes) {
		super(context, attributes);

		LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.month, this, true);
		
		monthTable = (TableLayout)findViewById(R.id.MonthTable);
		monthTitle = (TextView)findViewById(R.id.MonthTitle);
		sdf = new SimpleDateFormat("MMMMM yyyy");
	}
	
	public void setMonth(Activity activity, int year, int month) {
        java.util.Calendar theDay = getFirstSunOfMonth(year, month);
	        theDay.set(java.util.Calendar.HOUR_OF_DAY, 0);
	        theDay.set(java.util.Calendar.MINUTE, 0);
	        theDay.set(java.util.Calendar.SECOND, 0);
	        theDay.set(java.util.Calendar.MILLISECOND, 0);
                
        List<Calendar> calendars = CPSyncUtil.getInstance().getSelectedCalendars(activity);
        /*
        for (Calendar calendar:calendars) {
        	logger.info("Calendar=" + calendar.getId() + ":" + calendar.getDisplayName() + ":" + calendar.getColor());
        }
        */

        List<Instance> instances = CPSyncUtil.getInstance().getInstances(activity, calendars, theDay.getTime().getTime(), theDay.getTime().getTime()+42l*24l*60l*60l*1000l-1);
        //List<Instance> instances = CPSyncUtil.getInstance().getInstancesInThisMonth(activity, calendars);
        /*
        StringBuffer eventsStr = new StringBuffer();
        if (instances != null) {
            for (Instance instance: instances) {
            	eventsStr.append(instance.getEventId() + ":" + instance.getCalendarId() + ":" + instance.getTitle() + ":" + SimpleDateFormat.getDateTimeInstance().format(new Date(Long.valueOf(instance.getBegin()))) + ":" + SimpleDateFormat.getDateTimeInstance().format(Long.valueOf(instance.getEnd())));
            	eventsStr.append("\n");
            }
            logger.info("Events=" + eventsStr);
        }
        */

        int numWeeks = monthTable.getChildCount();
        TableRow weekRow;
        DayInMonthView dayInMonth;
        
        int instanceIndex = 0;
        Instance instance;
        java.util.Calendar tempCal = java.util.Calendar.getInstance();
        if (instances != null) {
        	tempCal.setTimeInMillis(Long.valueOf(instances.get(instanceIndex).begin));
        }
        
        //StringBuffer eventsStr;
        for (int week=1; week<numWeeks; ++week) {
        	weekRow = (TableRow)monthTable.getChildAt(week);
        	for (int day=0; day<7; ++day) {
        		dayInMonth = (DayInMonthView)weekRow.getChildAt(day);
        		dayInMonth.setDay(theDay.get(java.util.Calendar.DATE));
        		dayInMonth.setChiDay(new ChineseCalendar.SolarDate(
    				theDay.get(java.util.Calendar.YEAR),
    				theDay.get(java.util.Calendar.MONTH)+1,
    				theDay.get(java.util.Calendar.DATE)).toLunarDate().getDayDesc());
        		
        		if (theDay.get(java.util.Calendar.MONTH)+1 != month) {
        			dayInMonth.setDim();
        		} else if (day == 0) {
        			dayInMonth.setBackgroundResource(R.color.day_in_month_sun_bg);
        		} else if (day == 6) {
        			dayInMonth.setBackgroundResource(R.color.day_in_month_sat_bg);
        		} else {
        			dayInMonth.setBackgroundResource(R.color.day_in_month_bg);
        		}
        		
        		dayInMonth.clearEvents();
        		while (instances != null && instanceIndex < instances.size() &&
        				tempCal.get(java.util.Calendar.MONTH) == theDay.get(java.util.Calendar.MONTH) &&
        				tempCal.get(java.util.Calendar.DATE) == theDay.get(java.util.Calendar.DATE)) {
        			instance = instances.get(instanceIndex);
        			dayInMonth.addEvent(instance.title, instance.color);
        			
        			++instanceIndex;
        			if (instanceIndex < instances.size()) {
        				tempCal.setTimeInMillis(Long.valueOf(instances.get(instanceIndex).begin));
        			}
        		}
        		
        		theDay.add(java.util.Calendar.DATE, 1);
        	}
        }
        
        theDay.set(java.util.Calendar.YEAR, year);
        theDay.set(java.util.Calendar.MONTH, month-1);
        monthTitle.setText(sdf.format(theDay.getTime()));
	}
		
    // Get the first Sunday of the specified month (1-12)
	private java.util.Calendar getFirstSunOfMonth(int year, int month) {
    	java.util.Calendar calendar = java.util.Calendar.getInstance();
    	calendar.set(java.util.Calendar.YEAR, year);
    	calendar.set(java.util.Calendar.MONTH, month-1);
    	calendar.set(java.util.Calendar.DATE, 1);
    	int weekDay = calendar.get(java.util.Calendar.DAY_OF_WEEK);  // 1:Sun, 7:Sat
    	calendar.add(java.util.Calendar.DATE, -(weekDay-1));
    	
    	return calendar;
	}
}
